package com.training.web.controller;

import com.training.bean.Manager;
import com.training.jwt.JWTUtils;
import com.training.web.service.WebManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class WebLoginController {
    @Autowired
    private WebManagerService service;
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> login(@RequestParam String phone, @RequestParam String password) {
        System.out.println("Login attempt - Phone: " + phone + ", Password: " + password);

        // 查找管理员
        Manager manager = service.getManager(phone);
        Map<String, Object> result = new HashMap<>();
        
        System.out.println("Manager found: " + manager);
        
        // 验证管理员是否存在且密码正确
        if (manager != null && manager.getPassword() != null && manager.getPassword().equals(password)) {
            System.out.println("Login successful for manager: " + manager.getPhone());
            
            // 获取管理员ID和用户名，并将其放入payload
            Map<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(manager.id));
            payload.put("phone", manager.phone);
            payload.put("nickname", manager.nickname);
            payload.put("userType", "manager"); // 添加用户类型标识

            // 生成JWT的令牌
            String token = JWTUtils.getToken(payload);

            result.put("status", "success");
            result.put("token", token);
        } else {
            System.out.println("Login failed for phone: " + phone);
            result.put("status", "fail");
        }
        
        System.out.println("Returning result: " + result);
        return ResponseEntity.ok(result);
    }

}